package {
  import flash.display.MovieClip;
  import flash.display.Sprite;
  
  public class Antlion extends Sprite {
    static public const MAX_PULL_SPEED:Number = 3;
    static public const ANTLION_RADIUS:Number = 50;
    static public const DEATH_RADIUS:Number = 10;
	
	public var animation:MovieClip;
	private var cycles:Number = 0;
	
    public function Antlion(_x:int, _y:int) {
      x = _x;
      y = _y;
      
	 // graphics.beginFill(0x0000ff, 0.5);
      
	  /*
	  graphics.drawCircle(0, 0, ANTLION_RADIUS);
      graphics.endFill();
	  
	  graphics.beginFill(0x000000,0);
	  graphics.lineStyle(1, 0x555555, 1);
*/
	
	  
	  animation = new Main.Antlion_up;
	  animation.gotoAndStop(1);
    	addChild(animation);	  
    }
	
	public function update(people:Vector.<Person>):void {
		
		var closestPersonDist:Number = Number.MAX_VALUE;
		var closestPerson:Person = null;
		graphics.clear();
		
		cycles++;
		
		for each(var person:Person in people) {
			if (!person.alive) continue;
			
			var d:Number = Main.dist(person.x, person.y, x, y);
			
			if(d<ANTLION_RADIUS)
				person.danger = true;
			
			if( d < closestPersonDist)
				{
				closestPersonDist = d;
				closestPerson = person;
				}
			
		}
		
		
		//in the pit
		if(closestPersonDist < ANTLION_RADIUS)
			{
			for(var i:Number = 0; i<3; i++)
			{
				graphics.beginFill(0xFF0000, 0);
				graphics.lineStyle(.8, 0x888888, 1);
				graphics.drawCircle(0, 0, ANTLION_RADIUS - (cycles+i*ANTLION_RADIUS/3)%ANTLION_RADIUS);
				graphics.endFill();
			}
			
			animation.visible = true;
			
			//trace(cycles%100+" cycles");
			//frames up
			var f:Number = Math.floor(Main.map(closestPersonDist, ANTLION_RADIUS, DEATH_RADIUS, 1, 15));
			animation.gotoAndStop(f);
			var angle:Number = Math.atan2(closestPerson.y-y, closestPerson.x-x);
			animation.rotation = Main.toDegrees(angle)+90;
			}
		else
			animation.visible = false;
		
	}
	
	
	
  }
}